package cn.apthink.satoken;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;

import cn.apthink.model.VRole;
import cn.apthink.service.AuthService;
import cn.apthink.utility.Util;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 自定义权限加载接口实现类，完成 Sa-Token 的自定义权限验证扩展
 * @author David唐
 * @createdate 2024年1月21日
 */
@Slf4j
@Component
public class StpInterfaceImpl implements StpInterface {

	@Inject
	AuthService authService;

    /**
     * 返回一个账号所拥有的权限码集合
     */
	@SuppressWarnings("unchecked")
	@Override
    public List<String> getPermissionList(Object loginId, String loginType) {
    	log.debug("=>getPermissionList: " + loginId + "=>" + loginType);
    	SaSession session = StpUtil.getTokenSession();
    	Set<String> ps;
    	if (ObjectUtils.isNull(session.get("permission"))) {
        	Set<VRole> rs = authService.getRolesByUserUid((String)loginId);
        	ps = authService.getPermissionByRoles(rs);
        	session.set("permission", ps);
    	} else {
    		ps = (Set<String>) session.get("permission");
    	}
    	return new ArrayList<>(ps);
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
    	log.debug("=>getRoleList:" + loginId + " " + loginType);
    	Set<VRole> rs = authService.getRolesByUserUid((String)loginId);
    	if (Util.isEmpty(rs)) {
    		return new ArrayList<>();
    	} else {
    		return rs.stream().map(VRole::getId).toList();
    	}
    }

}
